package com.yzkj.siot.util;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Component;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.utils.IOUtils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class TencentCOSHelper {

	// 存储桶名称
	@Value("${cos.bucketName}")
	private String BUCKET_NAME;

	// secretId 秘钥id
	@Value("${cos.secretId}")
	private String SECRET_ID;

	// SecretKey 秘钥
	@Value("${cos.secretKey}")
	private String SECRET_KEY;

	// COS 区域
	@Value("${cos.region}")
	private String REGION;
	
	private COSClient createCosClient() {
		// 创建COS 凭证
		COSCredentials credentials = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);

		// 配置 COS 区域 就购买时选择的区域
		ClientConfig clientConfig = new ClientConfig(new Region(REGION));

		// 创建 COS 客户端连接
		COSClient cosClient = new COSClient(credentials, clientConfig);
		
		return cosClient;
	}
	
	public String readFile(String key) {

		COSClient cosClient = this.createCosClient();
		
		GetObjectRequest getObjectRequest = new GetObjectRequest(BUCKET_NAME, key);
		COSObjectInputStream cosObjectInput = null;

		try {
		    COSObject cosObject = cosClient.getObject(getObjectRequest);
		    cosObjectInput = cosObject.getObjectContent();
		} catch (CosServiceException e) {
			log.error("cos错误", e);
		} catch (CosClientException e) {
			log.error("cos错误", e);
		}

		// 处理下载到的流
		// 这里是直接读取，按实际情况来处理
		byte[] bytes = null;
		try {
		    bytes = IOUtils.toByteArray(cosObjectInput);
		    String filePath = "./tempFile_" + UUID.fastUUID().toString();
		    
		    FileUtil.writeBytes(bytes, filePath);
		    
		} catch (IOException e) {
			
		} finally {
		    // 用完流之后一定要调用 close()
		    try {
		    	if (cosObjectInput != null) {
		    		cosObjectInput.close();		    		
		    	}
			} catch (IOException e) {
				log.error("cos错误", e);
			} 
		}

		// 在流没有处理完之前，不能关闭 cosClient
		// 确认本进程不再使用 cosClient 实例之后，关闭之
		cosClient.shutdown();
		
		return null;
	}
	
	public String uploadFile(String moduleName, File file) {

		COSClient cosClient = this.createCosClient();
		String fileName = file.getName();
		try {
			String substring = fileName.substring(fileName.lastIndexOf("."));
			File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), substring);
			localFile = file;
			String key = moduleName + "/" + UUID.fastUUID().toString() + "/" + fileName;
			// 将 文件上传至 COS
			PutObjectRequest objectRequest = new PutObjectRequest(BUCKET_NAME, key, localFile);
			cosClient.putObject(objectRequest);
			
			Date expiration = new Date(new Date().getTime() + 15 * 60 * 1000);
			URL downloadUrl = cosClient.generatePresignedUrl(BUCKET_NAME, key, expiration);
			return "http://" + downloadUrl.getHost() + downloadUrl.getPath();
		} catch (Exception e) {
			log.error("上传cos失败 mouduleName => {}", moduleName, e);
		} finally {
			cosClient.shutdown();
		}
		
		return null;
	}

	public String uploadFile(String moduleName, MultipartFile file) {

		// 创建COS 凭证
		COSCredentials credentials = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);

		// 配置 COS 区域 就购买时选择的区域
		ClientConfig clientConfig = new ClientConfig(new Region(REGION));

		// 创建 COS 客户端连接
		COSClient cosClient = new COSClient(credentials, clientConfig);
		String fileName = file.getOriginalFilename();
		try {
			String substring = fileName.substring(fileName.lastIndexOf("."));
			File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), substring);
			file.transferTo(localFile);
			String key = moduleName + "/" + UUID.fastUUID().toString() + "/" + fileName;
			// 将 文件上传至 COS
			PutObjectRequest objectRequest = new PutObjectRequest(BUCKET_NAME, key, localFile);
			cosClient.putObject(objectRequest);
			
			Date expiration = new Date(new Date().getTime() + 15 * 60 * 1000);
			URL downloadUrl = cosClient.generatePresignedUrl(BUCKET_NAME, key, expiration);
			return "http://" + downloadUrl.getHost() + downloadUrl.getPath();
		} catch (Exception e) {
			log.error("上传cos失败 mouduleName => {}", moduleName, e);
		} finally {
			cosClient.shutdown();
		}
		
		return null;
	}
}
